package com.hncboy.chatgpt.front.voice;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Lists;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Tests {

    private static List<String> names = Lists.newArrayList("zh-CN-XiaoxiaoNeural");

    private static String uri = "https://southeastasia.api.speech.microsoft.com/accfreetrial/texttospeech/acc/v3.0-beta1/vcg/speak";

    public static void main(String[] args) throws IOException {
        String str = """
                尊敬的观众，欢迎收看今天的新闻联播。
                 """;
        String st1 = """
                首先，国家卫生健康委员会发布最新疫情通报，截至昨日24时，全国新增确诊病例10例，其中境外输入病例7例，本土病例3例。目前全国累计确诊病例已达到86831例。同时，全国各地正在积极推进疫苗接种工作，截至昨日，已累计接种疫苗超过1.5亿剂次。
                """;
        String st2 = """
                其次，国务院新闻办公室今天举行新闻发布会，介绍我国加强知识产权保护的相关情况。会上，有关部门表示，我国将加强知识产权保护，推进知识产权审查制度改革，加强知识产权司法保护，打击侵犯知识产权的违法行为，为创新发展提供更加有力的保障。
                """;
        String st3 = """
                最后，国家发改委今天发布数据显示，今年1-5月，我国固定资产投资同比增长15.4%，其中制造业投资同比增长21.6%，高技术制造业投资同比增长28.7%。这表明我国经济发展持续向好，各项政策措施正在发挥积极作用。
                """;
        String st4 = """
                以上就是今天的新闻联播，感谢您的收看。
                """;


        String name = "zh-CN-XiaoxiaoNeural";
        String style = "false";
        String role = "false";
        String rate = "10%";
        String pitch = "0%";
        extracted(st2, name, style, role, rate, pitch);
        /*List.of(str, st1, st2, st3, st4).forEach(v -> {
            try {
                extracted(v, name, style, role, rate, pitch);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });*/

    }

    private static void extracted(String str, String name, String style, String role, String rate, String pitch) throws IOException {
        HashMap<String, String> headers = new HashMap<>();
        headers.put("authority", "southeastasia.api.speech.microsoft.com");
        headers.put("accept", "*/*");
        headers.put("accept-language", "zh-CN,zh;q=0.9");
        headers.put("customvoiceconnectionid", "d8a3a480-dd87-11ed-8758-97b5a7fbfaf6");
        headers.put("origin", "https://speech.microsoft.com");
        headers.put("sec-ch-ua", "\"Google Chrome\";v=\"111\", \"Not(A:Brand\";v=\"8\", \"Chromium\";v=\"111\"");
        headers.put("sec-ch-mobile", "?0");
        headers.put("sec-ch-platform", "\"Windows\"");
        headers.put("sec-fetch-dest", "empty");
        headers.put("sec-fetch-mode", "cors");
        headers.put("sec-fetch-site", "same-site");
        headers.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36");
        headers.put("content-type", "application/json");
        headers.put("response-type", "arraybuffer");
        String ssml = """
                 <speak xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="http://www.w3.org/2001/mstts" 
                        xmlns:emo="http://www.w3.org/2009/10/emotionml" version="1.0" xml:lang="en-US">
                        <voice name="${Name}">
                            <mstts:express-as style="${Style}">
                                <prosody rate="${Rate}" pitch="${Pitch}">
                                ${Text}
                                </prosody>
                            </mstts:express-as>
                        </voice>
                    </speak>
                """;
        String replace = ssml.replace("${Text}", str)
                .replace("${Name}", name)
                .replace("${Style}", style)
                .replace("${Rate}", rate)
                .replace("${Pitch}", pitch);

        HashMap<String, Object> body = new HashMap<>();
        body.put("ssml", replace);
        body.put("ttsAudioFormat", "audio-24khz-160kbitrate-mono-mp3");
        body.put("offsetInPlainText", 0);
        body.put("properties", Map.of("SpeakTriggerSource", "AccTuningPagePlayButton"));

        HttpResponse execute = HttpRequest.post(uri).addHeaders(headers).body(JSONUtil.toJsonStr(body)).execute();
        //System.out.println(execute);
        InputStream inputStream = execute.bodyStream();
        //System.out.println(inputStream);

        String fileName = "测试.mp3";
        String path = creatFile(fileName);
        writeToLocal(path + "\\" + fileName, inputStream);
        System.out.println("*****" + path + "\\" + fileName + "-下载成功!");
    }

    /**
     * 创建文件
     *
     * @param fileName
     * @return
     */
    public static String creatFile(String fileName) {
        File parentFile = new File("E:\\music");
        File file = new File(parentFile, fileName);
        try {
            file.createNewFile();
            System.out.println(fileName + "-创建成功,正在写入并下载......");
            return file.getParent();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将InputStream写入本地文件
     *
     * @param destination 写入本地目录
     * @param input       输入流
     * @throws IOException
     */
    private static void writeToLocal(String destination, InputStream input)
            throws IOException {
        int index;
        byte[] bytes = new byte[1024];
        FileOutputStream downloadFile = new FileOutputStream(destination);
        while ((index = input.read(bytes)) != -1) {
            downloadFile.write(bytes, 0, index);
            downloadFile.flush();
        }
        downloadFile.close();
        input.close();
    }
}
